package de.stalinski.util;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class Beep {

    public Beep() {
    }

    public void beep() {
        try {
            generateTone(950, 50, 25, true);
        } catch (LineUnavailableException ex) {
            
        }
    }

    public void playWelcome() {
        try {
            generateTone(200, 100, 127, false);
            generateTone(300, 100, 127, false);
            generateTone(400, 100, 127, false);
            generateTone(500, 80, 127, false);
        } catch (LineUnavailableException ex) {
            Logger.getLogger(Beep.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void generateTone(int hz, int msecs, int volume, boolean addHarmonic)
            throws LineUnavailableException {

        float frequency = 44100;
        byte[] buf;
        AudioFormat af;
        if (addHarmonic) {
            buf = new byte[2];
            af = new AudioFormat(frequency, 8, 2, true, false);
        } else {
            buf = new byte[1];
            af = new AudioFormat(frequency, 8, 1, true, false);
        }
        SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
        sdl = AudioSystem.getSourceDataLine(af);
        sdl.open(af);
        sdl.start();
        for (int i = 0; i < msecs * frequency / 1000; i++) {
            double angle = i / (frequency / hz) * 2.0 * Math.PI;
            buf[0] = (byte) (Math.sin(angle) * volume);

            if (addHarmonic) {
                double angle2 = (i) / (frequency / hz) * 2.0 * Math.PI;
                buf[1] = (byte) (Math.sin(2 * angle2) * volume * 0.6);
                sdl.write(buf, 0, 2);
            } else {
                sdl.write(buf, 0, 1);
            }
        }
        sdl.drain();
        sdl.stop();
        sdl.close();
    }
}
